package com.zhkc.wisdom.common.login.filter;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.zhkc.wisdom.common.base.context.SecurityContextHolder;
import com.zhkc.wisdom.common.base.model.LoginContextInfo;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;

import java.io.IOException;

/**
 * 过滤器，把登录信息存入线程变量
 */
@Order(1)
@ConditionalOnProperty(prefix = "zhkc.login", name = "enabled", havingValue = "true", matchIfMissing = false)
@WebFilter(urlPatterns = {"/**"}, filterName = "securityFilter")
public class SecurityFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityFilter.class);


    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        try {
            StringBuilder url = new StringBuilder();
//            if (req instanceof HttpServletRequest) {
//                ParameterRequestWrapper httpReq = new ParameterRequestWrapper((HttpServletRequest) req);
//                url.append("[").append(httpReq.getRequestURL()).append("]-[").append(httpReq.getQueryString()).append("]");
//            }

            //获取用户信息,存入SecurityContextHolder
            SecurityContextHolder.setAuthObject(getLoginAccount());

            long reqtime = System.currentTimeMillis();
            chain.doFilter(req, res);
            long restime = System.currentTimeMillis() - reqtime;
            this.logger(restime, url);
        } finally {
            SecurityContextHolder.remove();
        }
    }

    private void logger(long time, StringBuilder url) {
        LOGGER.info(url.toString() + "<<< 接口执行时间： [{}]ms", time);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    private LoginContextInfo getLoginAccount() {
        if (StrUtil.isNotEmpty(StpUtil.getTokenInfo().getTokenValue())){
            LoginContextInfo loginContextInfo = new LoginContextInfo();
            Object obj = null;
            try {
                obj = StpUtil.getExtra("info");
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (obj != null) {
                loginContextInfo = BeanUtil.toBean(obj, LoginContextInfo.class);
            }
            return loginContextInfo;
        }
        return null;
    }
}
